package com.cqjtu.store.address.service.impl;

import com.cqjtu.store.address.mapper.AddressMapper;
import com.cqjtu.store.address.pojo.dto.AddressDTO;
import com.cqjtu.store.address.pojo.entity.Address;
import com.cqjtu.store.address.pojo.entity.District;
import com.cqjtu.store.address.pojo.vo.AddressUpdateVO;
import com.cqjtu.store.address.pojo.vo.AddressVO;
import com.cqjtu.store.address.pojo.vo.DistrictVO;
import com.cqjtu.store.address.service.AddressService;
import com.cqjtu.store.common.Constants;
import com.cqjtu.store.common.ServiceCode;
import com.cqjtu.store.common.ServiceException;
import com.cqjtu.store.user.pojo.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional //事务处理
@Slf4j
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public List<AddressVO> getAddressList(UserLoginVO userLoginVO){
        List<Address> addressList = addressMapper.getList(userLoginVO.getId());
        if(addressList.isEmpty()){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该用户没有地址");
        }
        //封装：将实体类封装的数据，转成VO供控制层调用
        List<AddressVO> addressVOList = new ArrayList<>();
        addressList.forEach(address ->{
            AddressVO addressVO = new AddressVO();
            addressVO.setId(address.getId());
            addressVO.setName(address.getName());
            addressVO.setPhone(address.getPhone());
            addressVO.setTag(address.getTag());
            addressVO.setIsDefault(address.getIsDefault());
            //详细地址：省份+城市+区县+小区编号
            addressVO.setAddressDetail(address.getProvinceName()+
                    address.getCityName()+address.getAreaName()+address.getAddress());
            addressVOList.add(addressVO);
        });
        return addressVOList;
    }

    @Override
    public void delete(Integer id, UserLoginVO userLoginVO) {
        // 判断这个地址是否存在
        Address address = addressMapper.getById(id);
        log.debug("地址信息:{}",address);
        if(address==null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该地址编号不存在");
        }
        //判断这个地址是否是属于当前用户
        if(address.getUserId() != userLoginVO.getId()){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"你没有权限删除该地址");
        }
        // 删除
        int result = addressMapper.delete(id);
        if(result != 1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"删除失败");
        }
    }

    @Override
    public void setDefault(Integer id, UserLoginVO userLoginVO) {
        // todo 判断id是否为空
        //判断当前地址是否属于当前用户
        Address address = addressMapper.getById(id);
        if(address == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"该地址不存在");
        }
        //判断地址是否属于这个用户
        if(address.getUserId() != userLoginVO.getId()){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"没有操作权限，不能设置默认");
        }
        //地址是属于当前用户的了
        //把当前用户的地址设置为非默认
        int result = addressMapper.setNunDefalut(userLoginVO.getId());
        if (result == 0){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"设置默认地址失败");
        }
        //设置默认
        address.setIsDefault(Constants.DEFALUT_ADDRESS);
        address.setModifiedUser(userLoginVO.getUsername());
        //设置当前地址默认
        result = addressMapper.setDefault(address);
        if(result !=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"设置默认地址失败");
        }
    }

    @Override
    public List<DistrictVO> getDistrictList(Integer parent) {
        if(parent == null){
            //查询的是省份
            parent = 86;
        }
        List<District> districtList = addressMapper.getDistrictList(parent);
        if(districtList.isEmpty()){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"没有数据");
        }
        List<DistrictVO> districtVOList = new ArrayList<>();
        //封装
        districtList.forEach(district -> {
            DistrictVO districtVO = new DistrictVO();
            districtVO.setCode(district.getCode());
            districtVO.setName(district.getName());
            districtVOList.add(districtVO);
        });
        return districtVOList;
    }

    /**
     * 新增地址
     * @param addressDTO
     * @param userLoginVO
     */
    @Override
    public void saveAddress(AddressDTO addressDTO, UserLoginVO userLoginVO) {
        // todo 根据地址编号去查询地址信息，判断地址对象中的地址名称跟传递过来的名称已否一致
        // todo 根据地址编号去查询地址信息
        // todo 判断这个地址的名称跟传递的名称是否一致
        District province = addressMapper.getByCode(addressDTO.getProvinceCode());
        if(province == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改的省份/直辖市地址编号有误");
        }
        if(!province.getName().equals(addressDTO.getProvinceName())){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"修改的省份/直辖市名称有误");
        }
        District city = addressMapper.getByCode(addressDTO.getCityCode());
        if(city == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改的省份/直辖市地址编号有误");
        }
        if(!city.getName().equals(addressDTO.getCityName())){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"修改的省份/直辖市名称有误");
        }
        District area = addressMapper.getByCode(addressDTO.getAreaCode());
        if(area == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改的省份/直辖市地址编号有误");
        }
        if(!area.getName().equals(addressDTO.getAreaName())){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"修改的省份/直辖市名称有误");
        }
        // 这里我们限制地址的条数为5条
        //查询当前用户的地址的数目
        int count = addressMapper.count(userLoginVO.getId());
        if(count == Constants.ADDRESS_MAX_TIMES){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"新增地址失败，地址最多条目数为"+Constants.ADDRESS_MAX_TIMES);
        }
        //封装地址
        Address address = new Address();
        address.setName(addressDTO.getName());
        address.setProvinceCode(addressDTO.getProvinceCode());
        address.setProvinceName(addressDTO.getProvinceName());
        address.setCityCode(addressDTO.getCityCode());
        address.setCityName(addressDTO.getCityName());
        address.setAreaCode(addressDTO.getAreaCode());
        address.setCityName(addressDTO.getCityName());
        address.setAddress(addressDTO.getAddress());
        address.setZip(addressDTO.getZip());
        address.setPhone(addressDTO.getPhone());
        address.setTel(addressDTO.getTel());
        address.setTag(addressDTO.getTag());
        //添加人名称
        address.setCreatedUser(userLoginVO.getUsername());
        //地址所属人的编号
        address.setUserId(userLoginVO.getId());
        int reslut = addressMapper.save(address);
        if(reslut!=1){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED,"新增地址失败");
        }

    }

    @Override
    public AddressUpdateVO getAddressById(Integer id, UserLoginVO userLoginVO) {
        //根据编号去查询地址
        Address address = addressMapper.getById(id);
        if(address == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"地址不存在");
        }
        //判断这个地址是否属于当前用户
        if(address.getUserId() != userLoginVO.getId()){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"没有权限获取该地址");
        }
        //封装成VO的形式返回:
        // todo 对象的拷贝.... hutools
        AddressUpdateVO addressUpdateVO = new AddressUpdateVO();
        addressUpdateVO.setId(address.getId());
        addressUpdateVO.setName(address.getName());
        addressUpdateVO.setProvinceCode(address.getProvinceCode());
        addressUpdateVO.setProvinceName(address.getProvinceName());
        addressUpdateVO.setCityCode(address.getCityCode());
        addressUpdateVO.setCityName(address.getCityName());
        addressUpdateVO.setAreaCode(address.getAreaCode());
        addressUpdateVO.setAreaName(address.getAreaName());
        addressUpdateVO.setAddress(address.getAddress());
        addressUpdateVO.setZip(address.getZip());
        addressUpdateVO.setPhone(address.getPhone());
        addressUpdateVO.setTel(address.getTel());
        addressUpdateVO.setTag(address.getTag());
        return addressUpdateVO;
    }

    /**
     * 修改地址
     * @param addressDTO 地址信息
     * @param userLoginVO 修改人
     */
    @Override
    public void update(AddressDTO addressDTO, UserLoginVO userLoginVO) {
        // todo 根据地址编号去查询地址信息，判断地址对象中的地址名称跟传递过来的名称已否一致
        // todo 根据地址编号去查询地址信息
        // todo 判断这个地址的名称跟传递的名称是否一致
        District province = addressMapper.getByCode(addressDTO.getProvinceCode());
        if(province == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改的省份/直辖市地址编号有误");
        }
        if(!province.getName().equals(addressDTO.getProvinceName())){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"修改的省份/直辖市名称有误");
        }
        District city = addressMapper.getByCode(addressDTO.getCityCode());
        if(city == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改的省份/直辖市地址编号有误");
        }
        if(!city.getName().equals(addressDTO.getCityName())){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"修改的省份/直辖市名称有误");
        }
        District area = addressMapper.getByCode(addressDTO.getAreaCode());
        if(area == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改的省份/直辖市地址编号有误");
        }
        if(!area.getName().equals(addressDTO.getAreaName())){
            throw new ServiceException(ServiceCode.ERR_CONFLICT,"修改的省份/直辖市名称有误");
        }
        //根据前端传来的数据获取地址编号
        Integer id = addressDTO.getId();
        if(id == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改的地址的编号不能为空");
        }
        //根据id查询地址
        Address address = addressMapper.getById(id);
        if(address == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"修改的地址不存在");
        }
        //判断这个地址是否属于当前用户
        if(address.getUserId() != userLoginVO.getId()){
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN,"没有权限修改");
        }
        //为地址重新设置值
        address.setName(addressDTO.getName());
        address.setProvinceCode(addressDTO.getProvinceCode());
        address.setProvinceName(addressDTO.getProvinceName());
        address.setCityCode(addressDTO.getCityCode());
        address.setCityName(addressDTO.getCityName());
        address.setAreaCode(addressDTO.getAreaCode());
        address.setCityName(addressDTO.getCityName());
        address.setAddress(addressDTO.getAddress());
        address.setZip(addressDTO.getZip());
        address.setPhone(addressDTO.getPhone());
        address.setTel(addressDTO.getTel());
        address.setTag(addressDTO.getTag());
        //设置修改人
        address.setModifiedUser(userLoginVO.getUsername());
        int reslut = addressMapper.update(address);
        if(reslut!=1){
            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED,"修改地址失败");
        }
    }

}

